<script setup>
import getArticle from '../api/getArticleById.js'
import isAdmin from '../api/isAdmin.js'
import getArticles from '../api/blurredArticles.js'
import record from '../api/recordUserInform'
import load from '../components/load.vue'
import {ref,reactive,onBeforeMount} from 'vue'
import commentBeUser from "./BeCommentToUser.vue"
import {useUserStore} from '../stores/user.js'
import { useRouter } from 'vue-router';
import { CircleCloseFilled,Mouse,Setting,Plus } from '@element-plus/icons-vue'
import userCard from "./userCard.vue"
import imageShow from './imageShow.vue'
// import comment from './comment.vue'
import getComment from "../api/comment.js"
import addComment from "../api/addComment.js"
import updateArticle from '../api/updateArticle.js'
import updateArticleAdmin from '../api/updateArticleAdmin'
import getUsername from "./getUsername.vue"
import getImageByUserId from "./userIdBeImage.vue"
const use = useRouter();
const imageUrl = ref("")
const image_id = ref("")
const comment = ref("");
const pop_flag = ref([])
const userInform = useUserStore() ;
const props =  defineProps({
    param:String
})
const replay = ref([])
const showImg = ref(false)
const visible = ref(false)
const an_state = ref(false)
const comments = ref([])
const article_id = ref("")
const url = "http://localhost:5173/api/image/upload?token=Bearer " + localStorage.getItem("jwttoken")
article_id.value = props.param
const showArticleImage_flag = ref(false)
setTimeout(() => {
        loading.value = false ;
    }, 3000);
const loading = ref(true)
const article = ref({
    title:"",
    content:"",
    type:"",
    author:"",
    authorCreatedTime:""
})
const userId = ref(localStorage.getItem("userId"))
const open = () => {
    ElNotification({
    title: '   不存在的文章   ',
    message: "你可以尝试通过搜索栏进行搜索",
    duration:1000
})
}

function add(){
    if(comment.value.trim() == ""){ ElMessage.error("你必须输入有效的内容") }
    else 
    addComment({
        content:comment.value ,
        userId:userInform.userId,
        status:true,
        articleId:props.param
    }).then(function(response){
        if(response.status == 200)
        { comment.value = ""
        getComment(props.param).then(function(response){
        if(response.status == 200)
        comments.value = response.data 
        setFlags()
        })
    }
    })
}

const recommand_article = ref({})

onBeforeMount(()=>{
    isAdmin().then((res)=>{
        if(res.status == 200)
        {
            an_state.value = true
        }
    })
    start_func()
})
const content = ref([]) ;

function setFlags (){
    for(let i = 0 ; i < comments.value.length() ;i++ )
    {
        pop_flag.value[i] = false
        replay.value[i] = ""
    }
}

const start_func = ()=>{
    getArticle(article_id.value).then(function(response)
{
    if (response.status == 200)
    {
        if(response.data != null && response.data!=undefined)
            article.value = response.data;
            
        if(userInform.userId!="")
        {
            loading.value=false
            if(article.userId!=userInform.userId)
            record({
                userId:userInform.userId,
                articleAdd:props.param
            }).then(function(response){
                if (response.status !== 200)
                console.error("response.status = " + response.status + "message = " + response.error)
            })
            getArticles("all",{
            search: article.value.title,
            page: 0,
            size: 6
            }).then((res)=>{
                if (res.status == 200)
                {
                    recommand_article.value = res.data;
                    console.log(recommand_article.value.length)
                    if(recommand_article.value.length < 6)
                    {
                        getArticles("type",{
                        type: article.value.type,
                        page: 0,
                        size: 6-recommand_article.value.length
                        }).then((res)=>{
                            if(res.status == 200)
                            {
                                for(let item of res.data)
                                recommand_article.value.push(item)

                            }
                        })
                    }
                    console.log(recommand_article.value)
                }
                
            })
            getComment(article.value.id).then(function(response){
            if(response.status == 200)
            comments.value = response.data 
                console.log(response.data )
            setFlags()
            })
        }
            console.log(article.value)
    }
    else {
        console.error("response.status = " + response.status + "message = " + response.error)
    }
})  // 获取article的实际内容

if(article === undefined )
{
    open()
    use.push("/")
}
}

function successHandler (res,file){ 
        image_id.value =res
        imageUrl.value = URL.createObjectURL(file.raw);
        article.value.imageId = image_id.value
    }
    function beforeAvatarUpload(file) {
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            ElMessage.error('上传头像图片只能是 JPG / PNG 格式!');
            }
            if (!isLt2M) {
            ElMessage.error('上传头像图片大小不能超过 2MB!');
            }


        return isJPG && isLt2M;
    }    

function updateArticleByDraw(){
    if(an_state.value && article.value.userId != localStorage.getItem("userId"))
    {
        console.log(article.value)
            updateArticleAdmin({
            id:article.value.id,
            state:article.value.state
            }).then((res)=>{
                if(res.status == 200)
                {
                    article.value = res.data
                    ElMessage.success("修改成功")
                }
            })
        }
        if(article.value.userId == localStorage.getItem("userId")) {
            console.log(article.value)
            updateArticle({
            id:article.value.id,
            author:article.value.author,
            content:article.value.content,
            state:article.value.state,
            imageId:article.value.imageId == null ? ""  : (article.value.imageId),
            images:article.value.images == null ?  "" : (article.value.images),
            title:article.value.title,
            type:article.value.type,
            userId:article.value.userId
            }).then((res)=>{
            if(res.status == 200)
            {
                article.value = res.data
                ElMessage.success("修改成功")
            }
        })
    }
}

function changeFunc(){
    sessionStorage.setItem("article_id",article.value.id)
    use.push("/articleCreate?article="+article.value.id)
}

function replayFunc(content,replay_id){
    if(content.trim() == ""){ ElMessage.error("你必须输入有效的内容") }
    else 
    addComment({
        content:content,
        userId:userInform.userId,
        status:true,
        articleId:props.param,
        replay:replay_id
    }).then(function(response){
        if(response.status == 200)
        { comment.value = ""
        getComment(props.param).then(function(response){
        if(response.status == 200)
        comments.value = response.data 
        setFlags()
        })
    }
    })
}

</script>

<template>
<div v-if="loading">
<load></load>
</div>
<div class="ArticleDisplay-box" v-else>
    <div class="card">
        <userCard :value="article.userId"></userCard>
        <el-card>
            <span>本文信息:</span>
            <div> <span style="font-size: 12px;">作者：{{ article.author }} &nbsp;&nbsp; <br>发布时间：{{article.authorCreatedTime}}</span></div>
            <div> <span style="font-size: 12px;">所属：<el-tag size="small">{{ article.type }}</el-tag></span></div>
            <div> <span style="font-size: 12px;">访问量：{{ article.visits }}</span> </div>
            <div> <span style="font-size: 12px;">本文封面:<br><imageShow @click="showArticleImage_flag = true , showImg = true" style="width: 100px; height: 100px;" :value="article.imageId"></imageShow></span> </div>
        </el-card>
        <br>
        <span style="font-size: 16px;">推荐：</span>
        <div style="width: 100%;height: 50vh;margin-top: 10px; padding: 1%;">
            <ul style="width: 100%;height: 100%;">
                <li style="width: 100%; height: 16%; margin-top: 1%;" v-for=" item in recommand_article" >
                    <el-card style="display: flex; width: 100%; height: 100%;" @click=" use.push('/redict?param='+item.id)">
                        <div><span> {{ item.title }} </span></div>
                        <div style="font-size: 12px;"><span > from：<getUsername :value="item.userId"></getUsername> </span>&nbsp;&nbsp; &nbsp;<el-icon><Mouse /></el-icon> {{ item.visits }}</div>
                    </el-card>
                </li>
            </ul>
        </div>
    </div>
    <div class="article-box">
    <el-card >
        <template #header>
            <div>
            <div class="title-box"> <h1>{{ article.title }}</h1> </div>
            </div>
        </template>

        <div>
            <div class="" v-html="article.content"></div>
        </div>

    </el-card>
    <div class="command_box"> 
            <div class="under-box">
                <textarea v-model="comment" style="width: 400px; height: 50px; margin-top: 0.5vh ; resize:none; font-size: 20px; border-radius: 50px; padding-left: 20px; padding-top: 5px; padding-right: 12px;"></textarea> <el-button @click="add" style="width: 100px; height: 40px; margin-top: 0.75vh; margin-left: 10px; border-radius: 10px;"> 提交 </el-button>
            </div>
        <el-divider />
        <el-card style="margin-top:6px"  v-for="(item, index) in comments" :key="index">
            <div class="command_card_box">
                <div style="position: relative; "><getImageByUserId :value="item.userId"></getImageByUserId></div>
                <div style=" position: relative; margin-left:20px ;">
                <div style="font-size: 12px;">
                    <span v-for="(item, index) in item.releaseTime " :key="index">{{ index>5?"":item }} {{ index==0?"年 ":index==1?"月 ":index==2?"日  | ":index<5?":":""}}</span>
                    <br>
                    <span>from：<getUsername :value=" item.userId "></getUsername> </span> &nbsp;&nbsp;&nbsp;&nbsp;<span v-if="item.replay!=null">回复：<commentBeUser :id='item.replay'></commentBeUser></span>
                </div>
                    <div class="command-content-box">
                        <div style="margin-top: 5px;">{{ item.content==""?"null":item.content }}</div> 
                        <div>
                            <br>
                            <el-popover :visible="pop_flag[index]" placement="right" :width="160">
                                <el-input v-model="replay[index]" style="width:130px" />
                                <div style="text-align: right; margin: 0">
                                    <el-button size="small" text @click="pop_flag[index] = false ">取消</el-button>
                                <el-button size="small" text @click="pop_flag[index] = false , replayFunc(replay[index],item.id) ">确定</el-button>
                                </div>
                                <template #reference>
                                    <el-link style="font-size: 14px;" @click="pop_flag[index] = true">回复</el-link>
                                </template>
                            </el-popover>
                            
                        </div>
                    </div>
                </div>

            </div>
            
        </el-card>
        </div>
    </div>
    </div>
    <div class="show-image-box" v-if="showArticleImage_flag">
        <div style="position: relative;left: 30px; top: 50px;"><CircleCloseFilled style="width: 30px; height: 30px;" @click="showArticleImage_flag = false , showImg = false"/></div>
        <imageShow v-if="showImg" @click="" style="position: relative; width: 40%; left: 30%; top: 10%;" :value="article.imageId"></imageShow>
    </div>

    <div class="setBox">
        <el-button v-if="an_state || userId == article.userId" @click="visible = true" size="large" :icon="Setting" circle></el-button>
    </div>
    

    <el-drawer style="z-index: 3;" v-model="visible" :show-close="false">
    <template #header="{ close, titleId, titleClass }">
        <h4 :id="titleId" :class="titleClass">{{ article.title }}</h4>
        <el-button type="danger" @click="close">
        <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
        Close
        </el-button>
    </template>
    <div>发布者：{{ article.userId }}&nbsp;&nbsp;&nbsp;编号：{{ article.id }}</div>
    <br>
    <div>类型：<el-input v-model="article.type"/></div>
    <br>
    <div>作者：<el-input v-model="article.author"/></div>
    <br>
    <div>发布日期：{{article.authorCreatedTime}} </div>
    <br>
    <div>
        封面：<br>
            <imageShow style="width: 160px; height: 160px;" :value="article.imageId"></imageShow>
        <el-upload
        class="avatar-uploader"
        :action="url"
        :show-file-list="true"
        :on-success = "successHandler"
        :before-upload="beforeAvatarUpload">
        
        <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
        <el-icon v-else class="el-icon-plus avatar-uploader-icon"> <Plus></Plus> </el-icon>
        </el-upload>
    </div>
    <br>
    内容：<br>
    <div> <el-link @click="changeFunc()"> 修改 </el-link></div>
    <br>
    <div v-if="article.state || an_state" >状态：<el-switch v-model="article.state"/></div>
    <div v-else>状态：<el-switch v-model="article.state" disabled/></div>
    <br>
    <div>
        <el-button @click="updateArticleByDraw()" text>
            提交  
        </el-button>
    </div>
</el-drawer>
</template>

<style>
    .command-content-box{
        width: 100%;
    }

    .command_card_box{
        display: flex;
        flex-direction:row; 
        margin-top:5px; 
        width: 100%; 
    }

    .setBox{
        position: absolute;
        top: 160px;
        left: 92%;
    }

    .command_box{
        height:140vh;
    }

    .under-box{
        margin-top:5%;
        width: 50vw;
        height: 5vh;
        display: flex;
    }


    .write-box {
        margin-top:20px;
        width: 100%;
        border-radius: 10px;
        margin-left:20%;
        position:absolute;
        top:90%
    }

    .ArticleDisplay-box{
        display: flex;
        position: absolute;
        top:140px;
        left: 8%;
        width: 84%;
    }

    .article-box{
        margin: 20px;
        position: relative;
        width: 93%;
        margin-left: 1%;
    }

    .show-image-box{
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100vw;
        height: 100%;
        z-index:9999;
        background-color:rgba(0, 0, 0, 0.466);
    }
    .card {
        z-index: 2;
        width: 300px;
    }
    .tops-box{
        width: 82%;
        position: relative;
        left: 8%;
        margin-top: 30px;
    }

    .title-box{
        width: 100%;
        padding: 20px;
        margin: auto;
    }

    .tips-box{
        position: relative;
        margin-left: 70% ;
    }

    .attribute-box{
        margin-top: 10px;
        display: flex;
        justify-content: center; 
        align-items: center; 
        margin-left: 72% ;
        width: 5vw;
        height: 3vh;
        border: 1px solid #888888;
        border-radius: 5px;
        background-color: #888888;
    }

    .tops-box > .content-box{
        left: 0%;
        margin-top: 3vh;
        width: 100%;
        height: auto;
        border-radius: 10px;
        background-color: #e6d6bf;
        padding: 30px;
        font-size: 18px;
    }
    .para{
        margin-top: 10px;
    }
</style>